import {MyNavBar} from '@/components'
import {useDetailHook, useListHook} from '@/hooks'
import {_getCommentDetail, _getReplyList, _isCollection,_delCollection, _postCollection} from './store'
import {queryString} from '@/utils'
import {history} from 'umi'
import {Toast, ActivityIndicator, Button, WhiteSpace} from 'antd-mobile'
import CommentItem from '../components/commentItem'
import './index.less'
import ReplyItem from './components/replyItem'
import {Footer, ShowLoading} from '@/components'
import {_postReply} from '@/pages/house/house/store'
import React from 'react'

function Comment() {
  const id = queryString('id')
  if (!id) {
    Toast.success('参数不正确')
    history.goBack()
  }

  const {detailData, loading} = useDetailHook({func: _getCommentDetail.bind(null, id)})

  let handleSearch = null

  const searchFunc = (onSearch) => {
    handleSearch = onSearch
  }

  const {data: replyList, showLoading} = useListHook({func: _getReplyList.bind(null, id), searchFunc})

  let handleSearch1 = null

  const searchFunc1 = (onSearch) => {
    handleSearch1 = onSearch
  }

  const {detailData: isCollection} = useDetailHook({func: _isCollection.bind(null, +id), searchFunc: searchFunc1})

  const postReply = async (content, rid) => {
    let temp = {}
    if (typeof rid === 'number') {
      temp = {
        content, rid
      }
    } else {
      temp = {
        content,
        cid: id
      }
    }
    const result = await _postReply(temp)
    if (result) {
      handleSearch()
      Toast.success('评论成功,请等待审核')
    }
  }

  const handleClick = async (status,id) => {
    let result = null
    if(status) {
      result = await _postCollection(id)
    } else {
      result = await _delCollection(id)
    }
    if(result) {
      handleSearch1()
      Toast.success('操作成功')
    }
  }

  return (<div>
    <MyNavBar title={detailData?.title || '标题'}/>
    <div className='comments'>
      {loading ? <ActivityIndicator toast/> :
        <CommentItem comment={{
          userUserInfoAvatar: detailData?.user?.userInfo?.avatar,
          userNickName: detailData?.user?.nickName,
          createdAt: detailData?.createdAt,
          title: detailData?.title,
          content: detailData?.content,
          pictures: detailData?.pictures,
          houseAddress: detailData?.house?.address
        }}/>
      }
      <WhiteSpace size='lg'/>
      {isCollection?.flag ? <Button onClick={() => {
        handleClick(0, detailData?.id)
      }} type='warning'>取消收藏</Button> : <Button onClick={() => {
        handleClick(1, detailData?.id)
      }} type='primary'>收藏</Button>}
      <WhiteSpace size='lg'/>
      <div className='reply'>
        <h1 className='reply-title'>评论列表</h1>
        {replyList?.length ? replyList.map(item => (
          <ReplyItem key={item.id} reply={item}/>
        )) : ''}
        <ShowLoading showLoading={showLoading}/>
      </div>
    </div>
    <Footer postReply={postReply}/>
  </div>)
}

export default Comment
